package cn.neusoft.controller;

import cn.neusoft.po.User;
import cn.neusoft.query.UserQuery;
import cn.neusoft.service.UserService;
import cn.neusoft.vo.ResponseObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    //注册
    @PostMapping("/app/reg/{code}")
    public ResponseObj register(@RequestBody User user,@PathVariable("code") Integer code,HttpSession session){

        if (user == null || user.getPhone()==null || "".equals(user.getPhone()) || code==null){
            return ResponseObj.ERROR(555,"参数校验失败");
        }

        Object smsCode = session.getAttribute("smsCode");
        if (smsCode!=null && smsCode.equals(code)){
            return userService.register(user);
        }

        return ResponseObj.ERROR(334,"注册失败");
    }

    //修改
   @PostMapping("/app/update")
   public ResponseObj update(@RequestBody User user){
       return userService.update(user);
   }

    //注销
   @DeleteMapping("/app/unreg/{id}")
   public ResponseObj unRegister(@PathVariable("id") Integer userId){
        return userService.unRegister(userId);
   }

    //登录
   @PostMapping("/app/log")
   public ResponseObj login(@RequestBody User user){
        return userService.login(user);
   }

    //分页查询
   @PostMapping("/page")
   public ResponseObj getByPgae(UserQuery userQuery){
        return userService.getByPgae(userQuery);
   }

    //通过id查询
   @GetMapping("/app/{id}")
   public ResponseObj getById(@PathVariable("id") Integer userId){
        return userService.getById(userId);
   }

    //通过手机号和验证码登录
   @GetMapping("/app/log/{phone}/{code}")
   public ResponseObj loginByPhone(@PathVariable("phone") String phone,@PathVariable("code") Integer validCode,HttpSession session){
       Object smsCode = session.getAttribute("smsCode");
       if (smsCode!=null && smsCode.equals(validCode)){
           return userService.loginByPhone(phone,validCode);
       }
       return ResponseObj.ERROR(333,"手机号登录失败");
   }

   @GetMapping("/app/sms")
   public ResponseObj getSmsCode(HttpSession session){
       int code = (int)(Math.random()*1000000);
       session.setAttribute("smsCode",code);
       return ResponseObj.SUCCESS(code);
   }

}
